package com.speedfall;

import com.speedfall.kafka.Produce;
import net.bytebuddy.implementation.bind.annotation.*;
import org.apache.log4j.Logger;

import java.lang.reflect.Method;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.Callable;

public class MyInteceptor extends BaseCtl{
	private static Logger logger = Logger.getLogger(MyInteceptor.class);
	@RuntimeType
	public static Object intercept(@Origin Method method,@AllArguments Object[] args,@This Object object,
									@SuperCall Callable<?> callable) throws Exception {
		Object resObj = null;
		try {
			// 原有函数执行
			resObj = callable.call();
			return resObj;
		} finally {
			String className = object.getClass().getName();
			logger.info(className);
			if(classNameList.contains(className)){
				if(methodNameList.contains(method.getName())){
					String str = bulidReturn(resObj,method,args);
					//logger.info(str);
					//向kafka推送消息
					new Produce().sendKafaMessage("speedfall",str);
				}
			}
		}
	}

	/**
	 * 输入文件
	 * @param
	 */
	/*public static void exitFile(String str) {
		String filePath = "F:/lkw.text";
		FileOutputStream fileOutputStream=null;
		OutputStreamWriter write=null;
		BufferedWriter writer = null;
		PrintWriter pw = null;
		try {
			fileOutputStream = new FileOutputStream(filePath,true);
			write = new OutputStreamWriter(fileOutputStream,"UTF-8");
			writer = new BufferedWriter(write);
			pw = new PrintWriter(writer);
			System.out.println("========"+str);
			pw.println(str);
		} catch (IOException e) {
			e.printStackTrace();
		}finally {
			pw.close();
			try {
				writer.close();
				write.close();
				fileOutputStream.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}*/

	private static String bulidReturn(Object obj, Method method,Object[] allArguments) {
		StringBuilder operationName = new StringBuilder(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss->").
					format(new Date())+method.toString().substring(0,method.toString().lastIndexOf("(")+1));
		for (int i = 0; i < method.getParameterTypes().length;i++) {
			operationName.append(method.getParameterTypes()[i].getName()).append(" ").append(allArguments[i]).append(",");
		}

		if (method.getParameterTypes().length > 0) {
			operationName = operationName.deleteCharAt(operationName.length() - 1);
		}
		String returnObj = null;
		if(obj!=null){
			returnObj = obj.toString();
		}
		operationName.append("){\n").append("\t\t\treturn:").append(obj).append("\n\t\t    }");
		return operationName.toString();
	}

}
